/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.content;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import model.contents.Content;
import model.inventory.InventoryTable;

import org.json.simple.JSONObject;

public class TableBox extends ContentBox {

    private JTable table;
    private InventoryTable tableModel;

    public TableBox(Content c, int width, int height) {
    	super(c, width, height);
		//setup table
    	if(!(content instanceof InventoryTable)) {
    		return;
    	}
    	this.setSize(new Dimension(width, height));
    	tableModel = (InventoryTable)c;
    	this.setOpaque(false);
        this.table = new JTable(tableModel.getVisibleRows(), tableModel.getFields());
    	//this.table = new JTable(generateArray(10), new Integer[] {1,2,3,4,5});
        table.setOpaque(false);
        table.setEnabled(false);
        table.setFillsViewportHeight(true);
        //table.setDefaultRenderer(Object.class, new TransparentBackgroundRenderer());
        table.setShowGrid(false);
        
        //setup table header
        table.setRowHeight(tableModel.getDefinition().getTableRowHeight());
        table.getTableHeader().setEnabled(false);
        table.getTableHeader().setOpaque(false);
        //table.getTableHeader().setDefaultRenderer(new TransparentBackgroundRenderer());
        table.setPreferredSize(new Dimension(width, height));
        this.packColumns(table, 0);
        //setup table box and put table into it
        this.setLayout(new BorderLayout());
        //To show table header, uncomment this line
        //this.add(table.getTableHeader(), BorderLayout.PAGE_START);
        this.setRenderer(new TransparentBackgroundRenderer(this));
        this.add(table, BorderLayout.CENTER);
    }

    public void setRowHeight(int height) {
        table.setRowHeight(height);
    }
    
    public void setRenderer(TableCellRenderer r) {
        this.table.setDefaultRenderer(Object.class, r);
    }

    public void setHeaderRenderer(TableCellRenderer r) {
        this.table.getTableHeader().setDefaultRenderer(r);
    }


    public void setColumnWidth(int columnNumber, int width) {
        TableColumn col = null;
        col = this.table.getColumnModel().getColumn(columnNumber);

        if(col==null) {
            return;
        }

        col.setPreferredWidth(width);
    }
    

    public void packColumns(JTable table, int margin) {
        for (int c = 0; c < table.getColumnCount(); c++) {
            packColumn(table, c, margin);
        }
    }

// Sets the preferred width of the visible column specified by vColIndex. The column
// will be just wide enough to show the column head and the widest cell in the column.
// margin pixels are added to the left and right
// (resulting in an additional width of 2*margin pixels).
    public void packColumn(JTable table, int vColIndex, int margin) {
        TableModel model = table.getModel();
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        
        Component comp = renderer.getTableCellRendererComponent(
                table, col.getHeaderValue(), false, false, 0, 0);
        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(
                    table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        // Set the width
        col.setPreferredWidth(width);
    }


    public JTable autoResizeColWidth(JTable table, DefaultTableModel model) {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setModel(model);

        int margin = 5;

        for (int i = 0; i < table.getColumnCount(); i++) {
            int vColIndex = i;
            DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
            TableColumn col = colModel.getColumn(vColIndex);
            int width = 0;

            // Get width of column header
            TableCellRenderer renderer = col.getHeaderRenderer();

            if (renderer == null) {
                renderer = table.getTableHeader().getDefaultRenderer();
            }

            Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);

            width = comp.getPreferredSize().width;

            // Get maximum width of column data
            for (int r = 0; r < table.getRowCount(); r++) {
                renderer = table.getCellRenderer(r, vColIndex);
                comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                        r, vColIndex);
                width = Math.max(width, comp.getPreferredSize().width);
            }

            // Add margin
            width += 2 * margin;

            // Set the width
            col.setPreferredWidth(width);
        }

        ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
                SwingConstants.LEFT);

        // table.setAutoCreateRowSorter(true);
        table.getTableHeader().setReorderingAllowed(false);

        return table;
    }


    static class TransparentBackgroundRenderer extends JLabel implements TableCellRenderer {
    	TableBox box;
        public TransparentBackgroundRenderer(TableBox box) {
            super();
            this.box = box;
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        	JLabel label =  new JLabel();
            label.setOpaque(false);
            JSONObject formatJSON= box.tableModel.getDefinition().getFormat((String)box.tableModel.getFields()[column]);
        	if(value!=null) {
        		label.setText(value.toString());
        		if(formatJSON!=null) {
            		LabelFormat format = new LabelFormat(formatJSON);
            		format.applyStyle(label);
            	}
        	}
        	return label;
        }
    }

    private Integer[][] generateArray(int width) {
    	Integer[][] arr= new Integer[10][width];
    	for(int i=0;i<10;i++) {
    		for(int j=0;j<width;j++) {
    			arr[i][j]=i*j;
    		}
    	}
    	return arr;
    }
}
